<template>
  <div ref="el" class="chart"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { onMounted, onBeforeUnmount, ref, watch, type PropType } from 'vue';

echarts.use([PieChart, TitleComponent, TooltipComponent, LegendComponent, CanvasRenderer]);

interface TagDatum { name: string; value: number }

const props = defineProps({
  data: { type: Array as PropType<TagDatum[]>, required: true },
  title: { type: String, default: '标签占比' }
});

const el = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;

function render() {
  if (!el.value) return;
  if (!chart) chart = echarts.init(el.value, undefined, { renderer: 'canvas' });
  chart.setOption({
    backgroundColor: 'transparent',
    title: { 
      text: props.title, 
      textStyle: { 
        color: '#f8fafc', 
        fontSize: 16,
        fontWeight: 'bold'
      } 
    },
    tooltip: { 
      trigger: 'item',
      backgroundColor: 'rgba(15, 23, 42, 0.9)',
      borderColor: 'rgba(37, 99, 235, 0.3)',
      textStyle: {
        color: '#f8fafc'
      }
    },
    legend: { 
      bottom: 0, 
      textStyle: { 
        color: '#f8fafc',
        fontSize: 12
      },
      pageTextStyle: {
        color: '#f8fafc'
      }
    },
    series: [
      {
        name: 'Tags',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 8, borderColor: '#ffffff', borderWidth: 2 },
        label: { show: false, position: 'center' },
        emphasis: { 
          label: { 
            show: true, 
            fontSize: 16, 
            fontWeight: 'bold', 
            color: '#f8fafc',
            backgroundColor: 'rgba(15, 23, 42, 0.8)',
            borderRadius: 4,
            padding: [4, 8]
          } 
        },
        labelLine: { show: false },
        data: props.data
      }
    ]
  });
}

const onResize = () => chart?.resize();

onMounted(() => { render(); window.addEventListener('resize', onResize); });
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); chart?.dispose(); chart = null; });
watch(() => props.data, render, { deep: true });
</script>

<style scoped>
.chart { width: 100%; height: 280px; }
</style>

